package com.bing.controller.util;

import com.bing.services.EnvService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.Locale;

/**
 * Created by kaibb on 15-12-26.
 */
@Controller
@RequestMapping("upload")
public class Upload {
    private static final Logger LOGGER = LoggerFactory.getLogger(Upload.class);
    public static final String EDITORMD_IMAGE_FILE = "editormd-image-file";
    @Autowired
    private MessageSource messageSource;

    @Autowired
    private EnvService envService;

    @RequestMapping(value = EDITORMD_IMAGE_FILE, method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public EditorImgStatus upload(@RequestPart(EDITORMD_IMAGE_FILE) MultipartFile file,Locale locale) {
        LOGGER.info("upload file:{} {},{}", EDITORMD_IMAGE_FILE, file.getOriginalFilename(), file.getSize());
        String fileUrl = envService.copyAndGetEditorFileUrl(file);
        String msg=messageSource.getMessage("editor.success", new Object[]{file.getOriginalFilename()}, locale);
        return createEditorImgStatus(fileUrl,msg);
    }

    private class EditorImgStatus {
        private int success; // 0 表示上传失败，1 表示上传成功
        private String message; //"提示的信息，上传成功或上传失败及错误信息等。",
        private String url;     //"图片地址"        // 上传成功时才返回

        public EditorImgStatus(int success, String message, String url) {
            this.success = success;
            this.message = message;
            this.url = url;
        }


        public int getSuccess() {
            return success;
        }

        public void setSuccess(int success) {
            this.success = success;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }

    private EditorImgStatus createEditorImgStatus(String url,String msg) {
        return new EditorImgStatus(1, msg, url);
    }
}
